<template>
    <div class="table">
        <div class="topBtn"> 
          <span>活动配置结果</span>
          <el-button type="primary" size="small" @click="openCondition">添加结果</el-button>
        </div>
        <el-table
        :data="resultListTable"
        border
        style="width: 100%">
            <el-table-column
                prop="id"
                label="结果ID"
                width="180">
            </el-table-column>
            <el-table-column
                prop="cond_id"
                label="条件ID">
            </el-table-column>
            <el-table-column
                prop="name"
                label="结果名称">
            </el-table-column>
            <el-table-column
                prop="code"
                label="结果代码">
            </el-table-column>
            <el-table-column
                prop="params"
                label="结果参数">
                <template slot-scope="scope">
                  <div v-if="scope.row.code!='VOUCHER_CATEGORY'">
                    {{scope.row.code=='VOUCHER'?scope.row.params.prize_id:scope.row.code=='DRAW_PRIZE'?scope.row.params.limit:scope.row.params.coupon_id}}
                  </div>
                  <div v-if="scope.row.code=='VOUCHER_CATEGORY'">
                    <p style="margin-bottom:0;" v-for="(item,index) in scope.row.params" :key="index"><b>（{{item.quantity}}）</b> 奖品ID：{{item.prize_id}}</p>
                  </div>
                </template>
            </el-table-column>
            <el-table-column
                label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="editCondition(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="delCondition(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- <div class="block">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </div> -->
        <!-- 添加条件弹框 -->
        <el-dialog title="添加结果" @closed="closedFn" width="45%" :visible.sync="dialogVisibleCondition">
          <!--  -->
            <div>
              <span>对应条件：</span>
              <el-select style="width:50%" value-key="key" v-model="conditionId" filterable placeholder="请选择对应条件">
                  <el-option
                  v-for="item in conditionListOk"
                  :key="item.id"
                  :label="`（${item.id}）${item.name}`"
                  :value="item.id">
                  </el-option>
              </el-select>
            </div>
            <div style="margin-top:30px;">
              <span>配置结果：</span>
              <el-select style="width:50%" value-key="key" v-model="resultValue" filterable placeholder="请选择配置结果">
                  <el-option
                  v-for="item in resultList"
                  :key="item.key"
                  :label="item.name"
                  :value="{name:item.name,key:item.key}">
                  </el-option>
              </el-select>
            </div>
            <el-dialog
                width="45%"
                title="配置活动结果"
                :close-on-click-modal="false"
                :visible.sync="innerVisible"
                @closed="innerClosedFn"
                append-to-body>
                <div class="conditionBox">
                  结果名称：{{resultValue.name}}
                  <div class="item" v-if="resultValue.key=='DRAW_PRIZE'"><span class="tit">抽奖次数：</span><el-input v-model="limit"></el-input></div>
                  <div class="item" v-else-if="resultValue.key=='COUPONS'">
                    <span class="tit">优惠券：</span>
                    <div>
                      <el-table
                        border
                        :data="couponList"
                        style="width: 100%">
                        <el-table-column
                          align="center"
                          width="50">
                          <template slot-scope="scope">
                            <el-radio v-model="coupon_id" :label="scope.row.id">{{''}}</el-radio>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="name"
                          align="center"
                          label="优惠券名称"
                          width="auto">
                        </el-table-column>
                      </el-table>
                      <pagination :total="couponTotal" v-model="couponPage" :pageSize.sync="couponPagesize" :pagesize="couponPagesize" :pageSizeOptions="pageSizeOptions" :showQuickJumper="true" @change="handleCouponPageChange" @onShowSizeChange="onShowSizeCouponChange"></pagination>
                    </div>
                    <!-- <el-radio-group v-model="coupon_id" v-infinite-scroll="loadCoupon">
                        <el-radio :label="item.id" v-for="(item,index) in couponList" :key="index">
                            {{item.name}}
                        </el-radio>
                    </el-radio-group> -->
                  </div>
                  <div v-else-if="resultValue.key=='VOUCHER' || resultValue.key=='VOUCHER_CATEGORY'">
                    <div class="item" v-if="resultValue.key=='VOUCHER'">
                      <span class="tit">获得张数：</span>
                      <el-input v-model="limitPrize" type="number" placeholder="请输入获得张数"></el-input>
                    </div>
                    <div v-if="resultValue.key=='VOUCHER'" style="margin-top:20px;">
                      <span class="tit">选择奖品：</span>
                      奖品ID：{{prize_id}}；
                      <el-button @click="addPrizeBtn('')">选择奖品</el-button>
                    </div>

                    <div class="item" style="" v-if="resultValue.key=='VOUCHER_CATEGORY'">
                      <span class="tit">品类配置：</span>
                      <div class="cateBox">
                        <div class="cateItem" v-for="(item,index) in quantityList" :key="index"><b>（{{item.quantity}}）</b>奖品ID：{{item.prize_id}}；<el-button @click="addPrizeBtn(index)" style="margin-left:10px;" size="medium">选择奖品</el-button><span class="spanBtn" @click="addQuantity(item.quantity)" v-if="index==quantityList.length-1">+</span><span class="spanBtn" v-if="index!=0 && index==quantityList.length-1" @click="reduceQuantity(index)">-</span></div>
                      </div>
                    </div>

                    <!-- 选择奖品对话框 -->
                    <el-dialog
                      title="选择奖品"
                      :visible.sync="dialogVisibleInnerPrize"
                      width="45%"
                      append-to-body>
                      <div class="item">
                        <span class="tit">奖品：</span>
                        <div>
                          <div style="display:flex;justify-content: flex-end;margin-bottom:5px;">
                            <el-input v-model="searchPrize" placeholder="请输入奖品名称" clearable @input="clearPrizeFn"></el-input>
                            <el-button type="primary" size="small" @click="searchPrizeFn">搜索</el-button>
                          </div>
                          <el-table
                            border
                            :data="prizeList"
                            style="width: 100%">
                            <el-table-column
                              align="center"
                              width="50">
                              <template slot-scope="scope">
                                <el-radio v-model="prize_id" :label="scope.row.id">{{''}}</el-radio>
                              </template>
                            </el-table-column>
                            <el-table-column
                              prop="date"
                              align="center"
                              label="奖品主图"
                              width="80">
                              <template slot-scope="scope">
                                <img style="width:30px;height:30px;" :src="scope.row.img" alt="">
                              </template>
                            </el-table-column>
                            <el-table-column
                              prop="name"
                              align="center"
                              label="奖品名称"
                              width="auto">
                            </el-table-column>
                            <el-table-column
                              prop="stock"
                              align="center"
                              label="库存"
                              width="auto">
                            </el-table-column>
                          </el-table>
                          <pagination :total="prizeTotal" v-model="prizePage" :pageSize.sync="prizePagesize" :pagesize="prizePagesize" :pageSizeOptions="pageSizeOptions" :showQuickJumper="true" @change="handlePrizePageChange" @onShowSizeChange="onShowSizePrizeChange"></pagination>
                        </div>
                      </div>
                      <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisibleInnerPrize = false">取 消</el-button>
                        <el-button type="primary" @click="selectPrizeSubmit">确 定</el-button>
                      </span>
                    </el-dialog>
                    
                  </div>
                </div>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="innerVisible = false">取 消</el-button>
                  <el-button type="primary" @click="addCondition">确 定</el-button>
                </div>
            </el-dialog>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleCondition = false">取 消</el-button>
                <el-button type="primary" @click="conditionNext">下一步</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import pagination from '@/common/pagination.vue'
export default {
    props:{
        activityId:{
            type:Number,
            default:''
        },
        marketId:{
          type:Number,
          default:''
        }
    },
    components:{
      pagination,
    },
    data(){
        return{
            page:1,
            pagesize:10,
            total:0,
            conditionListTable:[],
            resultListTable:[],
            conditionListOk:[],//已经添加的条件
            
            conditionId:'',//选择的条件id

            // 结果框
            dialogVisibleCondition:false,
            resultList:[], //结果列表
            resultValue:{}, //结果选中
            innerVisible:false,
            conditionMoney:'',//订单金额
            conditionRank:'',//用户数
            resultId:'',//结果id

            // resultName:'',//结果名称
            limit:'',//抽奖次数
            coupon_id:'',//优惠券id
            couponList:[],//优惠券列表
            couponPage:1,
            couponPagesize:5,
            couponTotal:0,

            prizeList:[],
            prize_id:'',//奖品id
            prizePage:1,
            prizePagesize:5,
            prizeTotal:0,
            searchPrize:'',
            limitPrize:1,//奖品个数

            // quantity:2,//跨品类数
            quantityIndex:'',//当前选择奖品的下标
            dialogVisibleInnerPrize:false,
            quantityList:[{quantity:2,limit:1,prize_id:''}],

            pageSizeOptions:[5,10,15,20]
        }
    },
    methods: {
      // 获取已添加条件列表
      getConditionOk(){
        let params = {
                activity_id:this.activityId
            }
            this.$http.post('/api/root/activity/cond/lists',params).then(res=>{
                console.log(res,'条件列表');
                if(res.code==1){
                    this.conditionListOk = res.data?res.data:[];
                    this.total = res.data.total
                }
            })
      },

        // 获取已配置结果列表
        getResultList(){
            let params = {
                activity_id:this.activityId
            }
            this.$http.post('/api/root/activity/result/lists',params).then(res=>{
                console.log(res,'奖品结果');
                if(res.code==1){
                    this.resultListTable = res.data?res.data:[];
                    this.total = res.data.total
                }
            })
        },

        // 添加品类配置条数
        addQuantity(num){
          this.quantityList.push({
            quantity:(num*1)+2,
            limit:1,
            prize_id:''
          })
        },
        //减少品类配置条数
        reduceQuantity(index){
          this.quantityList.splice(index,1)
        },
        // 选择奖品按钮
        addPrizeBtn(index){
          console.log(index,'/////');
          this.quantityIndex = index
          this.dialogVisibleInnerPrize = true
          this.getPrizeList()
        },
        // 选择奖品对话框确定
        selectPrizeSubmit(){
          if(!this.prize_id){
            this.$message.warning('请选择奖品')
            return
          }
          if(this.resultValue.key=='VOUCHER_CATEGORY'){
            let index = this.quantityIndex
            this.quantityList[index].prize_id = this.prize_id
          }
          this.dialogVisibleInnerPrize = false
        },

        // 删除条件
        delCondition(id){
            this.$confirm('此操作将删除该结果, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(()=>{
              let params = {
                activity_id:this.activityId,
                id
              }
              this.$http.post('/api/root/activity/result/del',params).then(res=>{
                console.log(res);
                if(res.code==1){
                  this.getResultList();
                  this.$message({
                    type:'success',
                    message:'删除成功'
                  })
                }else{
                  this.$message.warning(res.msg)
                }
              })
            })
        },

        // 编辑按钮
        async editCondition(row){
            console.log(row,'---');
            this.resultId = row.id
            this.conditionId = row.cond_id
            this.dialogVisibleCondition = true
            await this.getConditionOk()
            await this.getCondition()
            // this.innerVisible = true
            let indexCond = this.resultList.findIndex(item=>item.key==row.code)
            this.resultValue = {name:this.resultList[indexCond].name, key:row.code}
            if(row.code=='DRAW_PRIZE'){
              this.limit = row.params.limit
            }else if(row.code=='COUPONS'){
              this.getRootCouponList()
              this.coupon_id = row.params.coupon_id
            }else if(row.code=='VOUCHER'){
              this.getPrizeList()
              this.prize_id = row.params.prize_id
              this.limitPrize = row.params.limit
            }else if(row.code=='VOUCHER_CATEGORY'){
              this.getPrizeList()
              this.quantityList = row.params
            }
        },

        
        // 获取平台优惠券
        getRootCouponList(type){
          let params = {
            is_platform:1,
            page:this.couponPage,
            pagesize:this.couponPagesize
          }
          this.$http.post('/api/root/CouponShop/getCouponLists',params).then(res=>{
            console.log(res,'优惠券列表');
            if(res.code==1){
              this.couponList = res.data.lists?res.data.lists:[]
              this.couponTotal = res.data.count
            }
          })
        },
        //优惠券分页
        handleCouponPageChange(pageno, pagesize){
            this.couponPage = pageno;
            this.couponPagesize = pagesize;
            this.getRootCouponList()
        },
        onShowSizeCouponChange(current, size) {
          console.log(current,size,'fenye');
            this.couponPage = current;
            this.couponPagesize = size;
            this.getRootCouponList()
        },

        
        // 获取奖品列表
        getPrizeList(type){
          let params = {
            keyword:this.searchPrize,
            page:this.prizePage,
            pagesize:this.prizePagesize,
            market_id:this.marketId
          }
          this.$http.post('/api/root/activity/prize/lists',params).then(res=>{
            console.log(res,'优惠券列表');
            if(res.code==1){
              this.prizeList = res.data.data?res.data.data:[]
              this.prizeTotal = res.data.count
            }
          })
        },
        // 奖品搜索
        searchPrizeFn(){
          this.prizePage = 1
          this.prizePagesize = 5
          this.getPrizeList()
        },
        // 清空搜索
        clearPrizeFn(){
          if(this.searchPrize==''){
            this.prizePage = 1
            this.prizePagesize = 5
            this.getPrizeList()
          }
        },
        //奖品分页
        handlePrizePageChange(pageno, pagesize){
            this.prizePage = pageno;
            this.prizePagesize = pagesize;
            this.getPrizeList()
        },
        onShowSizePrizeChange(current, size) {
          console.log(current,size,'fenye');
            this.prizePage = current;
            this.prizePagesize = size;
            this.getPrizeList()
        },
        
        // 打开结果选择框
        openCondition(){
          this.dialogVisibleCondition = true;
          this.getConditionOk()
          this.getCondition()
        },
        // 获取可配置结果
        async getCondition(){
          await this.$http.post('/api/root/activity/result/config').then(res=>{
            console.log(res,'结果列表');
            if(res.code==1){
              let arr = []
              for(let key in res.data){
                res.data[key].key = key
                arr.push(res.data[key])
              }
              this.resultList = arr
              console.log(this.resultList,'////');
            }
          })
        },
        // 选择条件后下一步
        conditionNext(){
          if(!this.conditionId){
            this.$message.warning('请选择已添加条件')
            return
          }
          if(!Object.keys(this.resultValue).length){
            this.$message.warning('请选择结果')
            return
          }
          this.innerVisible = true;
          if(this.resultValue.key=='COUPONS'){
            this.getRootCouponList()
          }
          // else if(this.resultValue.key=='VOUCHER' || this.resultValue.key=='VOUCHER_CATEGORY'){
          //   this.getPrizeList()
          // }
        },
        // 添加条件确定
        addCondition(){
          let obj = {};
          if(this.resultValue.key=='DRAW_PRIZE'){
            obj.limit = this.limit
          }else if(this.resultValue.key=='COUPONS'){
            if(!this.coupon_id){
              this.$message.warning('请选择优惠券') 
              return
            }
            obj.coupon_id = this.coupon_id
          }else if(this.resultValue.key=='VOUCHER'){
            if(!this.prize_id){
              this.$message.warning('请选择奖品') 
              return
            }
            if(this.limitPrize*1<1){
              this.$message.warning('奖品个数最少为1')
              this.limitPrize = 1
              return
            }
            obj.limit = this.limitPrize?this.limitPrize:1;
            obj.prize_id = this.prize_id;
          }else if(this.resultValue.key=='VOUCHER_CATEGORY'){
            for(let i = 0;i < this.quantityList.length;i++){
              if(!this.quantityList[i].prize_id){
                this.$message.warning('请选择奖品')
                return
              }
            }
            obj = this.quantityList
            console.log(obj,'qqqqq');
          }else{}

          let params = {
            id:this.resultId,
            activity_id:this.activityId,
            cond_id:this.conditionId,
            params:obj,
            name:this.resultValue.name,
            code:this.resultValue.key
          }
          this.$http.post('/api/root/activity/result/save',params).then(res=>{
            console.log(res,'添加条件结果');
            if(res.code == 1){
              this.$message.success(this.resultId?'修改成功':'添加成功')
              this.innerVisible = false;
              this.dialogVisibleCondition = false;
              this.resultValue = {}
              this.getResultList()
            }else{
              this.$message.warning(res.msg)
            }
          })
        },

        // 关闭对话框后
        closedFn(){
          if(this.resultId){
            this.getResultList()
          }
            this.resultValue = {}
            this.resultId = ''
            this.conditionId = ''
        },

        // 关闭子对话框
        innerClosedFn(){
          if(this.resultId){
              // this.dialogVisibleCondition = false;
          }
          this.limitPrize = 1;
          this.prizePage = 1;
          this.prizePagesize = 5;
          this.couponPage = 1;
          this.couponPagesize = 5;
          this.searchPrize = '';
          this.prize_id = '';
          this.coupon_id = '';
          this.quantityIndex = '';
          this.quantityList = [{quantity:2,limit:1,prize_id:''}]
        },

        handleSizeChange(val){
            this.page = 1
            this.pagesize = val
            this.getResultList()
        },
        handleCurrentChange(val){
            this.page = val
            this.getResultList()
        }
    },
}
</script>

<style lang="less">
.table{
    padding-bottom: 20px;
    .block{
        display: flex;
        justify-content: flex-end;
        padding-top: 20px;
    }
}
.topBtn{
    display:flex;
    align-items:center;
    margin-bottom:15px;
    span{
        font-weight:600;
        margin-right:10px;
    }
}

.conditionBox{
  .item{
    display: flex;
    // align-items: center;
    margin-top: 15px;
    .tit{
      width: 70px;
      text-align: right;
    }
    .cateBox{
      .cateItem{
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        .spanBtn{
          width: 28px;
          height: 28px;
          border-radius: 50%;
          border: 1px solid #ccc;
          text-align: center;
          font-size: 18px;
          line-height: 28px;
          margin-left: 10px;
        }
      }
    }
    .el-input{
      width: 30%;
      margin-right: 10px;
    }
    .el-radio-group{
      width:100%;
      display:flex;
      flex-direction: column;
      overflow:auto;
      height:200px;
      .el-radio{
        img{
          width:30px;
          height:30px;
        }
        margin: 10px 0;
      }
    }
  }
}
</style>

